<?php

namespace app\site\controller\index;

use app\common\exception\MiException;
use app\model\sys\UploadFile;
use app\service\FileService;
use app\service\upload\UploadService;
use app\site\controller\AController;
use app\site\middleware\CheckLogin;
use app\site\service\SiteAuthService;
use think\db\exception\DbException;
use think\Request;

class UploadController extends AController
{
    /**
     * 只需要验证登录，不需要验证权限的请求
     */
    protected array $middleware = [CheckLogin::class];

    /**
     * @throws MiException
     */
    public function uploadImg(): \think\response\Json
    {
        $uploadSer = new UploadService();
        $siteId = SiteAuthService::instance()->getSiteId();
        $file = $uploadSer->setSubPath("/site/{$siteId}")->upload($siteId);
        return jsonSuccess([
            'file' => $file
        ]);
    }

    public function uploadFile(Request $request): \think\response\Json
    {
        $uploadSer = new UploadService();
        $siteId = SiteAuthService::instance()->getSiteId();
        $disk = $request->param('disk',  'public');
        try {
            $file = $uploadSer->setDisk($disk)->setSubPath("/site/{$siteId}")->upload($siteId);
        }  catch (\Exception $e){
            return jsonError($e->getMessage());
        }
        return jsonSuccess([
            'file' => $file
        ]);
    }

    public function uploadVideo(): \think\response\Json
    {
        $uploadSer = new UploadService();
        $siteId = SiteAuthService::instance()->getSiteId();
        try {
            $file = $uploadSer->setSubPath("/site/{$siteId}")->upload($siteId);
        }  catch (\Exception $e){
            return jsonError($e->getMessage());
        }
        return jsonSuccess([
            'file' => $file
        ]);
    }

    public function dirs(): \think\response\Json
    {
        $siteId = SiteAuthService::instance()->getSiteId();
        $list = UploadFile::where('site_id', $siteId)->where('uid', 0)->group('file_dir')->column('file_dir');
        return jsonSuccess([
            'items' => $list
        ]);
    }

    /**
     * @throws DbException
     */
    public function files(Request $request): \think\response\Json
    {

        $limit = $request->param('limit');
        $where = [];
//        if ($dir) $where[] = ['file_dir', '=', $dir];
//        if ($type) $where[] = ['type', 'like', '%'.$type.'%'];
        $list = UploadFile::where('site_id', SiteAuthService::instance()->getSiteId())->where('uid', 0)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total()
        ]);
    }

}
